package com.heima.behavior.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper,ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    /**
     * like点赞行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1. 检查参数(在controller中已通过注解检查)
        //2. 查询行为实体数据
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry =
                apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if(apBehaviorEntry==null){
         return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的行为实体不存在");
        }
        //3.根据实体查询点赞行为数据
        ApLikesBehavior apLikesBehavior = this.getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
        .eq(ApLikesBehavior::getEntryId,user.getId())
        .eq(ApLikesBehavior::getArticleId,dto.getArticleId()));

        //4.如果查询到的点赞行为数据不存在 且 dto中的行为为点赞,则保存点赞数据
        if(apLikesBehavior==null && dto.getOperation().equals(ApLikesBehavior.Operation.LIKE)){
            apLikesBehavior.setEntryId(user.getId());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setCreatedTime(new Date());
            this.save(apLikesBehavior);
            return ResponseResult.okResult();
        }
        //4.5如果点赞行为数据已存在,则提示勿重复点赞
        if(apLikesBehavior!=null && dto.getOperation().equals(ApLikesBehavior.Operation.LIKE)){
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
        }

        //5.如果点赞行为数据存在 且 dto中行为为取消点赞,则删除点赞数据
        if(apLikesBehavior!=null && dto.getOperation().equals(ApLikesBehavior.Operation.CANCEL)) {
            this.remove(Wrappers.<ApLikesBehavior>lambdaQuery()
                    .eq(ApLikesBehavior::getEntryId,apBehaviorEntry.getId())
                    .eq(ApLikesBehavior::getArticleId,dto.getArticleId()));
        }
        return ResponseResult.okResult();
    }
}
